package swu.cx.applyjurisdictiontest

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*

const val REQUEST_PERMISSIONS = 1
class MainActivity : AppCompatActivity() {
    private lateinit var myApp:MyApp
    val permissions = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.INTERNET
    )
    val requiresPermissions = mutableListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myApp = application as MyApp
        //添加activity
        myApp.addActivity(this)
        button.setOnClickListener {
            applyJurisdictions()
        }
    }

    private fun applyJurisdictions(){
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            permissions.forEach {
                if (ContextCompat.checkSelfPermission(this,it)!=PackageManager.PERMISSION_GRANTED){
                    requiresPermissions.add(it)
                }
            }
            if (requiresPermissions.size>0){
                requestPermissions(requiresPermissions.toTypedArray(),REQUEST_PERMISSIONS)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode== REQUEST_PERMISSIONS){
            grantResults.forEach {
                if (it!=PackageManager.PERMISSION_GRANTED){
                    //没有获取到权限就强制退出app
                    Log.v("cx","请求失败！")
                    myApp.exitApp()
                }else{
                    Toast.makeText(this,"申请权限成功！",Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}